package cn.edu.ustc.brainor.ustcgate;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;
import java.util.Objects;
import java.util.logging.Filter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

        一键上网();
        自动连接WiFi();
        setSupportActionBar(toolbar);
        测试内容();


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        //noinspection SimplifiableIfStatement
        if (id == R.id.about) {
            builder.setMessage("献给左祖奇\n" +
                    "直接点击\"一键上网\"自动连接第一通道的永久时长模式" +
                    "\n\n" +
                    "作者: 欧伟科\n" +
                    "联系方式: Brainor@qq.com\n" +
                    "you know where to find me \"3\"")
                    .setTitle("中科大网络通");
            builder.create().show();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public class netInteract extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... webHTMLs) {
            return new NetworkConnect().连接网络通();
        }

        @Override
        protected void onPostExecute(String htmlText) {
//            htmlText = new String(htmlText.getBytes("gb2312"),StandardCharsets.UTF_8);
            Matcher matcher = Pattern.compile("(?<=信息：)[\\s\\S]+?(?=</td>)").matcher(htmlText);
            matcher.find();
            TextView textView = (TextView) findViewById(R.id.textView);
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                textView.setText(Html.fromHtml(matcher.group(), Html.FROM_HTML_MODE_LEGACY));
            } else {
//                textView.setText(Html.fromHtml(matcher.group()));
            }
//            super.onPostExecute(htmlText);
        }
    }

    /**
     * 动态注册
     */
    private BroadcastReceiver myReceiverTest = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(context, intent.getAction() + "我爱你", Toast.LENGTH_SHORT)
                    .show();
        }
    };

    void 测试内容() {
        IntentFilter filterTest = new IntentFilter();
        filterTest.addAction("android.intent.action.MEDIA_BUTTON");
        filterTest.setPriority(Integer.MAX_VALUE);
        registerReceiver(myReceiverTest, filterTest);
    }

    private void 一键上网() {
        Button 一键上网_Button = (Button) findViewById(R.id.button);
        一键上网_Button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new netInteract().execute();
            }
        });
    }

    private void 自动连接WiFi() {
        TextView ustcnetStat_TextView = (TextView) findViewById(R.id.ustcnetStat_TextView);
        Button ustcnetStat_Button = (Button) findViewById(R.id.ustcnetStat_Button);
        final WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
        final List<WifiConfiguration> wifiConfigurationList = wifiManager.getConfiguredNetworks();
        int configurationIndex = 0;
        while (!Objects.equals(wifiConfigurationList.get(configurationIndex).SSID, "\"plasma\"")) {
            configurationIndex += 1;
        }
        if (configurationIndex > 0 && configurationIndex < wifiConfigurationList.size()) {
            ustcnetStat_Button.setTag(new int[]{wifiConfigurationList.get(configurationIndex).status, wifiConfigurationList.get(configurationIndex).networkId});
            ustcnetStat_Button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    int[] tag = (int[]) view.getTag();
                    switch (tag[0]) {
                        case WifiConfiguration.Status.DISABLED:
                            wifiManager.enableNetwork(tag[1], false);
                            break;
                        case WifiConfiguration.Status.ENABLED:
                            wifiManager.disableNetwork(tag[1]);
                            break;
                        case WifiConfiguration.Status.CURRENT:
                            wifiManager.disconnect();//之后会自动连上么?
                            break;
                    }
                    自动连接WiFi();//点击之后重新输出界面
                }
            });
            switch (wifiConfigurationList.get(configurationIndex).status) {
                case WifiConfiguration.Status.DISABLED:
                    ustcnetStat_TextView.setText("ustcnet已关闭自动连接");
                    ustcnetStat_Button.setText("enbale");

                case WifiConfiguration.Status.ENABLED:
                    ustcnetStat_TextView.setText("ustcnet已自动连接");
                    ustcnetStat_Button.setText("disable");
                case WifiConfiguration.Status.CURRENT:
                    ustcnetStat_TextView.setText("先断开ustcnet");
                    ustcnetStat_Button.setText("断开");
            }
        } else {
            ustcnetStat_Button.setVisibility(View.INVISIBLE);
            ustcnetStat_TextView.setText("没有找到WiFi，赶紧联系欧伟科");
        }
    }
}
